<?php

namespace app\services;

use app\level\LevelFactory;
use app\payment\PayFactory;
use EasyWeChat\Factory;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserNameCardBg;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\UserPropertyLog;
use Webman\Config;

class NameCardService
{

    public static function paySuccess($userId, $orderNo = '')
    {
        $inviteCode = self::generateInviteCode();
        $user = User::where('id', $userId)->first();
        $user->is_namecard = 1;
        $user->invite_code = $inviteCode;
        $user->save();

        if ($orderNo) {
            $order = Order::where('order_no', $orderNo)->first();

//            UserService::addTeamConsume($user['id'], $order['price']);

            if ($user['parent_id'] > 0) {
                LevelFactory::create($user['parent_id'])->recommendOpenNameCardRebate($order['price']);
            }

            if ($user['grant_parent_id'] > 0) {
                LevelFactory::create($user['grant_parent_id'])->indirectRecommendOpenNameCardRebate($order['price']);
            }

            $order['pay_time'] = date('Y-m-d H:i:s');
            $order['status'] = Order::STATUS_FINISH;
            $order->save();
        }

        self::generateInviteQrcode($inviteCode);
    }

    public static function bgs()
    {
        $list = UserNameCardBg::all()->toArray();

        foreach ($list as $key=>$item) {
            $list[$key]['thumb'] = full_url($item['thumb']);
        }

        return $list;
    }

    public static function generateInviteCode()
    {
        return 'I' . substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 9);
    }

    public static function generateInviteQrcode($userId, $inviteCode)
    {
        $config = ConfigService::getByGroup('wechat');
        $app = Factory::miniProgram([
            'app_id' => $config['wechat_app_id'],
            'secret' => $config['wechat_app_secret'],
            'response_type' => 'array'
        ]);

        $response = $app->app_code->get('/pages/public/account/wxLogin?invite_code=' . $inviteCode, [
            'env_version' => ConfigService::get('wechat_mini_program_code_version')
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->saveAs(public_path() . '/mini_program_qrcode', $inviteCode . '.png');
            $inviteQrcodeUrl = full_url('/mini_program_qrcode/' . $inviteCode . '.png');
            UserProfile::where('user_id', $userId)->update(['invite_qrcode_url' => $inviteQrcodeUrl]);

            return $inviteQrcodeUrl;
        }

        return '';
    }
}